package com.example.weatherforecast;


import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.example.weatherforecast.base.BaseFragment;
import com.example.weatherforecast.bean.WeatherBean;
import com.example.weatherforecast.database.MyDataBaseManager;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * 显示城市天气的复用fragement
 */
public class CityWeatherFragment extends BaseFragment implements View.OnClickListener {

    // 控件
    TextView tempTv, cityTv, conditionTv, windTv, tempRangeTv, dateTv;
    TextView clothIndexTv, carIndexTv, coldIndexTv, sportIndexTv, rayIndexTv;
    TextView clothTv, carTv, coldTv, sportTv, rayTv;

    LinearLayout futureLayout;
    ScrollView outLayout;

    //城市名称
    String city;

    // 除了地理位置外的访问地址，需要拼接
    String url1 = "http://api.map.baidu.com/telematics/v3/weather?location=";
    String url2 = "&output=json&ak=FkPhtMBK0HTIQNh7gG4cNUttSTyr0nzo";
    // 存放指数信息
    private List<WeatherBean.ResultsBean.IndexBean> indexList;

    public CityWeatherFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_city_weather, container, false);

        init(view);
        // 通过activity所传的地理位置获取到当前fragment加载的是那个地方的天气情况
        Bundle bundle = getArguments();
        city = bundle.getString("city");
        // 拼接url，获取完整的访问地址
        String url = url1 + city + url2;
        // 获取数据
        loadData(url);
        return view;
    }

    /**
     * 请求成功后回滚的方法
     *
     * @param result 结果
     */
    @Override
    public void onSuccess(String result) {
        // 解析并展示数据
        parseAndShowData(result);
        // 更新数据
        int count = MyDataBaseManager.updateInfoByCity(city, result);
        // 更新数据失败，即插入该条数据
        if (count <= 0) {
            MyDataBaseManager.addCityInfo(city, result);
        }
    }

    /**
     * 解析并展示数据
     *
     * @param result
     */
    private void parseAndShowData(String result) {
        // 使用gson解析数据，并封装到WeatherBean
        WeatherBean weatherBean = new Gson().fromJson(result, WeatherBean.class);

        // 获取当天的数据
        WeatherBean.ResultsBean resultsBean = weatherBean.getResults().get(0);
        // 获取指数信息集合列表
        indexList = resultsBean.getIndex();
        // 展示日期和城市数据
        dateTv.setText(weatherBean.getDate());
        cityTv.setText(resultsBean.getCurrentCity());
        // 获取今日天气情况
        WeatherBean.ResultsBean.WeatherDataBean todayDataBean = resultsBean.getWeather_data().get(0);
        windTv.setText(todayDataBean.getWind());
        tempRangeTv.setText(todayDataBean.getTemperature());
        conditionTv.setText(todayDataBean.getWeather());
        // 获取实时天气温度情况，需要处理字符串
        String[] split = todayDataBean.getDate().split("：");
        String todayTemp = split[1].replace(")", "");
        tempTv.setText(todayTemp);
        // 设置显示的天气情况图片,由于图片风格不一致，去掉图片显示
        //Picasso.with(getActivity()).load(todayDataBean.getDayPictureUrl()).into(dayIv);

        //获取未来三天的天气情况
        List<WeatherBean.ResultsBean.WeatherDataBean> futureList = resultsBean.getWeather_data();
        // 删除当天天气情况
        futureList.remove(0);
        // 将未来三天的天气情况加载到forecastLayout当中
        for (int i = 0; i < futureList.size(); i++) {
            View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.item_forecast, null);
            itemView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            futureLayout.addView(itemView);
            TextView idateTv = itemView.findViewById(R.id.itemForecastTvDate);
            TextView iconTv = itemView.findViewById(R.id.itemForecastTvCondition);
            TextView itemprangeTv = itemView.findViewById(R.id.itemForecastTvTemperature);
            ImageView iIv = itemView.findViewById(R.id.itemForecastIv);
            // 获取对应的位置的天气情况
            WeatherBean.ResultsBean.WeatherDataBean dataBean = futureList.get(i);
            idateTv.setText(dataBean.getDate());
            iconTv.setText(dataBean.getWeather());
            itemprangeTv.setText(dataBean.getTemperature());
            Picasso.with(getActivity()).load(dataBean.getDayPictureUrl()).into(iIv);
        }


        // 展示指数信息
        WeatherBean.ResultsBean.IndexBean indexBean = indexList.get(0);
        String msg = indexBean.getZs() + "\n" + indexBean.getDes();
        clothIndexTv.setText(msg);
        indexBean = indexList.get(1);
        msg = indexBean.getZs() + "\n" + indexBean.getDes();
        carIndexTv.setText(msg);
        indexBean = indexList.get(2);
        msg = indexBean.getZs() + "\n" + indexBean.getDes();
        coldIndexTv.setText(msg);
        indexBean = indexList.get(3);
        msg = indexBean.getZs() + "\n" + indexBean.getDes();
        sportIndexTv.setText(msg);
        indexBean = indexList.get(4);
        msg = indexBean.getZs() + "\n" + indexBean.getDes();
        rayIndexTv.setText(msg);

    }

    /**
     * 重写请求失败后回滚的方法
     * 即联网请求失败，将数据库中原来数据进行解析并展示数据
     *
     * @param ex
     * @param isOnCallback
     */
    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        // 数据库当中查找上一次信息
        String result = MyDataBaseManager.queryInfoByCity(city);
        // 如果查找结果不为空，进行解析并展示数据
        if (!TextUtils.isEmpty(result)) {
            parseAndShowData(result);
        }
    }

    private void init(View view) {
        //用于初始化控件操作
        tempTv = view.findViewById(R.id.fragTvTemperature);
        cityTv = view.findViewById(R.id.fragTvCity);
        conditionTv = view.findViewById(R.id.fragTvCondition);
        windTv = view.findViewById(R.id.fragTvWind);
        tempRangeTv = view.findViewById(R.id.fragTvTempRange);
        dateTv = view.findViewById(R.id.fragTvDate);
        clothIndexTv = view.findViewById(R.id.clothTv);
        carIndexTv = view.findViewById(R.id.washCarTv);
        coldIndexTv = view.findViewById(R.id.coldTv);
        sportIndexTv = view.findViewById(R.id.sportTv);
        rayIndexTv = view.findViewById(R.id.rayTv);
        clothTv = view.findViewById(R.id.cloth);
        carTv = view.findViewById(R.id.washCar);
        coldTv = view.findViewById(R.id.cold);
        sportTv = view.findViewById(R.id.sport);
        rayTv = view.findViewById(R.id.ray);
        futureLayout = view.findViewById(R.id.fragForecast);

        //设置点击事件的监听
        clothIndexTv.setOnClickListener(this);
        carIndexTv.setOnClickListener(this);
        coldIndexTv.setOnClickListener(this);
        sportIndexTv.setOnClickListener(this);
        rayIndexTv.setOnClickListener(this);
        clothTv.setOnClickListener(this);
        carTv.setOnClickListener(this);
        coldTv.setOnClickListener(this);
        sportTv.setOnClickListener(this);
        rayTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // 选择对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        switch (v.getId()) {
            case R.id.clothTv:
            case R.id.cloth:
                builder.setTitle("穿衣指数");
                WeatherBean.ResultsBean.IndexBean indexBean = indexList.get(0);
                String msg = indexBean.getZs() + "\n" + indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.washCarTv:
            case R.id.washCar:
                builder.setTitle("洗车指数");
                indexBean = indexList.get(1);
                msg = indexBean.getZs() + "\n" + indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.coldTv:
            case R.id.cold:
                builder.setTitle("感冒指数");
                indexBean = indexList.get(2);
                msg = indexBean.getZs() + "\n" + indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.sportTv:
            case R.id.sport:
                builder.setTitle("运动指数");
                indexBean = indexList.get(3);
                msg = indexBean.getZs() + "\n" + indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.rayTv:
            case R.id.ray:
                builder.setTitle("紫外线指数");
                indexBean = indexList.get(4);
                msg = indexBean.getZs() + "\n" + indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
        }
        // 显示对话框
        builder.create().show();
    }
}
